package com.millstein.service.impl;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.millstein.enums.BizCodeEnum;
import com.millstein.exception.BizException;
import com.millstein.properties.OSSProperties;
import com.millstein.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @description:
 * @author: tsing
 * @create: 2021-09-12 22:03
 */
@Service
@Slf4j
@EnableConfigurationProperties(OSSProperties.class)
public class FileServiceImpl implements FileService {

    @Autowired
    private OSSProperties ossProperties;

    /**
     * 上传图片
     *
     * @param file 图片的信息
     * @return
     */
    @Override
    public String uploadImage(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessId(),
                ossProperties.getAccessSecret());
        String fileName = DateUtil.now().replaceAll("-", "/").substring(0, 10)
                + "/"
                + UUID.randomUUID().toString().toUpperCase().replaceAll("-", "")
                + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        try {
            // 上传图片。参数1：bucket名字；参数2：文件名；参数3：图片输入流
            ossClient.putObject(ossProperties.getBucketName(), fileName, file.getInputStream());
        } catch (Exception e) {
            log.info("[上传图片]失败，原因是{}", e.getMessage());
            throw new BizException(BizCodeEnum.FILE_UPLOAD_USER_IMG_FAIL);
        } finally {
            ossClient.shutdown();
        }
        return "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint() + "/" + fileName;
    }
}
